#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->url->setText("ws://localhost:10000");
    setWindowTitle("WebSocket -客户端");
    connect(&m_client, &QWebSocket::connected, this, [=](){
        ui->recvMsgInfo->append("恭喜, 连接服务器成功!");
        m_client.sendTextMessage("你好, 服务器!");
    });
    connect(&m_client, &QWebSocket::disconnected, this, [=](){
        ui->recvMsgInfo->append("服务器已经断开了和客户端的连接!");
    });
    connect(&m_client, &QWebSocket::textMessageReceived, this, [=](const QString& msg){
        ui->recvMsgInfo->append("服务器: " + msg);
    });
    connect(ui->sendBtn, &QPushButton::clicked, this, [=](){
        QString msg = ui->sendMsgInfo->toPlainText();
        m_client.sendTextMessage(msg);
        ui->recvMsgInfo->append("客户端: " + msg);
        ui->sendMsgInfo->clear();
    });
    connect(ui->connectBtn, &QPushButton::clicked, this, [=](){
        QString url = ui->url->text();
        m_client.open(url);
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}
